import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/brn/brn_delete_tag.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/tree_mode.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/site/site_observer_detail/models/observer_model.dart';
import 'package:yt_devops/pages/site/site_observer_detail/site_observer_detail_model.dart';
import 'package:yt_devops/pages/site/site_observer_list/site_observer_list_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';

import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/services/site/site_services.dart';

class SiteObserverDetailController extends GetxController {
  SiteObserverDetailModel state = SiteObserverDetailModel();
  DeviceServices service = Get.put(DeviceServices());
  SiteServices siteServices = Get.put(SiteServices());
  final GlobalKey deleteKey = GlobalKey();
  late double deleteContainerHeight = 0;

  //已选中的站点列表
  late List<ObserverModel> selectedSites;
  List<TreeNode> treeData = [];
  late int siteId;
  late YtBrnDeleteTagController tagController;

  int type = 2; //2代表充电量、发电量、用电量 3代表放电量、上网电量 4代表功率
  List<ObserverModel> observerList = []; //当前需要展示采集点的列表,选择二级菜单后请求网络获取
  List<String> allSelectedObserver = []; //保存所有已选的采集点的名字,可能有重复的
  List<String> allObserverSelectName = []; //保存所有已选的采集点选中name,到时候需要看哪些是选中的
  List<ObserverModel> allSelectedObserverModelList = []; //保存所有已选的采集点模型,到时候模型转字典
  final siteObserverListController = Get.put(SiteObserverListController());

  @override
  void onInit() {
    if (Get.arguments != null) {
      siteId = Get.arguments['siteId'];
      type = Get.arguments['type'];
      Log.d('dataList==${Get.arguments['dataList']}');
      if (Get.arguments['dataList'] != null) {
        List list = Get.arguments['dataList'];
        for (var item in list) {
          allSelectedObserver.add(item['paramName']);
          allObserverSelectName.add(item['selectName'].toString());
          allSelectedObserverModelList.add(ObserverModel.fromJson(item));
        }
        tagController = YtBrnDeleteTagController(initTags: allSelectedObserver);
      }
    }
    super.onInit();
    loadData();
  }

  @override
  void onReady() {
    if (deleteKey.currentContext != null) {
      deleteContainerHeight = deleteKey.currentContext!.size!.height;
    }
  }

  @override
  void onClose() {}

  ///一进来就去加载数据
  loadData() {
    Configs.httpClient.requestWithLoading(() async {
      List data = await service.deviceTree({'siteId': siteId,});
      if (data.isNotEmpty) {
        List subList = data[0]['children'] as List;
        if (subList.isNotEmpty) {
          treeData = getTreeData(subList);

          update();
        }
      }
    });
  }

  ///获取选择的采集点的列表
  getObserverData(String deviceId, String paramName) async {
    var paramName = '电量';
    if (type == 4) {
      paramName = '功率';
    }
    showLoading(toast: ResKey.loading.tr);
    List data = await service.deviceTreeObserver({
      'siteId': siteId,
      'deviceId': deviceId,
      'paramName': paramName,
    }, onError: (error) {
      handleException(error);
      dismissLoading();
      return false;
    });
    dismissLoading();
    observerList.clear();
    for (var item in data) {
      observerList.add(ObserverModel.fromJson(item));
    }
    if (deleteKey.currentContext != null) {
      deleteContainerHeight = deleteKey.currentContext!.size!.height;
    }
    update();
    Log.d('observerList==' + observerList.length.toString());
  }

  ///确认
  confirm() {
    List<dynamic> dataList = [];
    for (var element in allSelectedObserverModelList) {
      if (allObserverSelectName.contains(element.selectName)) {
        dataList.add(element.toJson());
      }
    }
    siteObserverListController.savePostData(dataList, type);
    Get.back();
  }

  ///清空所有选择
  clearChoose() {
    for (var element in observerList) {
      element.flag = false;
    }
    tagController.setTags([]);
    allSelectedObserver.clear();
    allObserverSelectName.clear();
    allSelectedObserverModelList.clear();
    deleteContainerHeight = 0;
    update();
  }

  ///删除选择的采集点
  deleteSiteTag(int index) {
    for (var element in observerList) {
      if (tagController.tags.contains(element.showName)) {
        element.flag = true;
      } else {
        element.flag = false;
      }
    }
    tagController.setTags(allSelectedObserver);
    deleteContainerHeight = deleteKey.currentContext!.size!.height + 20;

    if (allSelectedObserverModelList.isEmpty) {
      deleteContainerHeight = 20;
    }
    update();

    ///这里需要做延迟加载 不然无法得到context的真实高度
    Future.delayed(const Duration(milliseconds: 50), () {
      // 延迟执行的代码
      deleteContainerHeight = deleteKey.currentContext!.size!.height;
      update();
    });
  }

  List<TreeNode> getTreeData(List data) => treeData = TreeNode.listFrom(
      source: data,
      value: (index, item) => item['id'],
      title: (index, item) => item['deviceName'],
      subNodes: (index, item) => getTreeData(item['children']));

  handleSave() {}
}
